// Copyright 2025 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

#include "absl/container/btree_set.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"

int main(int argc, char* argv[]) {
  // Expect: <out> <src1.x> [<src2.x> ...]
  if (argc < 3) {
    std::cerr << "Usage: " << argv[0]
              << " <output_path> <file1.x> [file2.x ...]\n";
    return 1;
  }

  std::filesystem::path out_path = argv[1];

  // Keeps unique & sorted automatically.
  absl::btree_set<std::string> names;

  for (int i = 2; i < argc; ++i) {
    std::filesystem::path p(argv[i]);
    if (p.extension() != ".x") {
      std::cerr << "Error: unexpected non-.x input file '" << p << "'.\n";
      return 1;
    }
    names.insert(p.stem().string());
  }

  std::ofstream out(out_path);
  if (!out) {
    std::cerr << "Failed to open output path: " << out_path << "\n";
    return 1;
  }

  out << "// Generated by " << argv[0] << "\n";

  std::string names_str =
      absl::StrJoin(names, "\n", [](std::string* out, const std::string& name) {
        absl::StrAppendFormat(out, "    \"%s\",", name);
      });
  out << absl::StrFormat(
      "inline constexpr std::array<std::string_view, %d> "
      "kDslxStdlibBuiltins = {\n%s\n};\n",
      names.size(), names_str);

  return 0;
}
